// 文章分类路由函数
const db = require('../db')

const sel = 'select * from ev_article_cate WHERE is_delete=0 ORDER BY id ASC'
const sleadd = 'select * from  ev_article_cate where  name=?'
const insert = 'insert into ev_article_cate set?'
const upd = 'update ev_article_cate set is_delete=1 where=?'
const selId = 'select * from ev_article_cate WHERE is_delete=0 and id=? '
const updateD = 'update ev_article_cate set ? WHERE id=? '

exports.cates = (req, res) => { //获取文章信息
  db.query(sel, (err, results) => {
    if (err) return res.cc('sql写入失败')
    if (results.length <= 0) return res.cc('获取文章失败')
    
    // 向前端返回
    res.send({
      status: 0,
      message: '获取文章分类成功',
      date: results
    })
  })

}
exports.addcates = (req, res) => { //新增
  db.query(sleadd, req.body.name, (err, results) => {
    if (err) return res.cc('sql写入失败')
    if (results.length > 0) return res.cc('哦豁，重复了')
    db.query(insert, req.body, (err, results) => {
      if (err) return res.cc('sql写入失败')
      if (results.affectedRows !== 1) return res.cc(0, '添加失败')
      res.cc(0, '添加分类成功')
    })

  })
}
exports.deletecate = (req, res) => { // 删除
  db.query(upd, (err, results) => {
    if (err) return res.cc('sql写入失败')
    if (results.affectedRows !== 1) return res.cc(0, '添加失败')
    res.cc(0, '删除分类成功')
  })
}

exports.getidcates = (req, res) => {
  db.query(selId, req.params.id, (err, results) => {
    if (err) return res.cc('sql写入失败')
    if (results.length <= 0) return res.cc('获取文章失败')
    res.send({
      status: 0,
      message: '获取文章分类成功',
      date: results
    })
  })
}
exports.updatecate = (req, res) => {
  db.query(sleadd, req.body.name, (err, results) => {
    if (err) return res.cc('sql写入失败')
    if (results.length <= 0) return res.cc('哦豁，重复了')
    console.log([req.body, req.body.id]);
    db.query(updateD, [req.body, req.body.id], (err, results) => {
      if (err) return res.cc('sql写入失败')
      if (results.affectedRows !== 1) return res.cc('修改失败')
      res.cc(0, '修改分类成功')
    })

  })
}
